package com.smy.baseutil.excel;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;

import lombok.extern.slf4j.Slf4j;

/**
 * @Title: ExcelUtil.java
 * @Description: excel读写工具类
 * @author zhoutao
 * @date 2019年1月9日 上午11:11:39
 * @version V1.0
 */
@Slf4j
public class ExcelUtil {

	/**
	 * Excel文件读取，默认读取sheet1
	 * 
	 * @param file
	 * @param sheet
	 * @return
	 */
	public static List<Object> readExcel(File file) throws IOException {

		return readExcel(file, new Sheet(1, 0));
	}

	/**
	 * Excel的文件读取，默认读取sheet1 返回java对象
	 * 
	 * @param file
	 * @param sheet
	 * @return
	 */
	public static List<Object> readExcel(File file, Class<? extends BaseRowModel> clazz) throws IOException {

		return readExcel(file, new Sheet(1, 0, clazz));
	}

	/**
	 * Excel的文件读取
	 * 
	 * @param file
	 * @param sheet
	 * @return
	 */
	public static List<Object> readExcel(File file, Sheet sheet) throws IOException {
		InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
		List<Object> data = EasyExcelFactory.read(inputStream, sheet);
		inputStream.close();
		return data;
	}

	/**
	 * Excel的文件读取
	 * 
	 * @param file
	 * @param sheet
	 * @return
	 */
	public static AnalysisEventListener readExcel(File file, Sheet sheet, AnalysisEventListener eventListener)
			throws IOException {
		InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
		EasyExcelFactory.readBySax(inputStream, sheet, eventListener);
		inputStream.close();
		return eventListener;
	}

	public static void writeExcel(File file, List<? extends BaseRowModel> data) throws IOException {
		if(data ==null || data.isEmpty()){
			return;
		}
		OutputStream out = new FileOutputStream(file);
		ExcelWriter writer = EasyExcelFactory.getWriter(out);
		Sheet sheet1 = new Sheet(1, 1);

		Table table = new Table(1);
		table.setClazz(data.get(0).getClass());
		writer.write(data, sheet1, table);

		writer.finish();
		out.close();

	}
	
	public static void writeExcel(HttpServletResponse response, String fileName, List<? extends BaseRowModel> data) throws IOException {
		if(data ==null || data.isEmpty()){
			return;
		}
		response.setHeader("Content-disposition", "attachment;filename="+fileName+".xlsx");
		OutputStream out = response.getOutputStream();
		ExcelWriter writer = EasyExcelFactory.getWriter(out);
		Sheet sheet1 = new Sheet(1, 1);

		Table table = new Table(1);
		table.setClazz(data.get(0).getClass());
		writer.write(data, sheet1, table);

		writer.finish();
		out.close();

	}

}
